package com.ygxsk.carhome.ui.signature;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.FileSignatureManage;
import com.ygxsk.carhome.response.FileSignatureOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.FileSignatureItemAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-10-26  13:52
 * @Description:已经完整签约的文件的历史记录
 */
public class SignatureSumHistoryActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshLayoutInSumHistorySignature)
    SmartRefreshLayout refreshLayoutInSumHistorySignature;

    @BindView(R.id.recyclerViewInSumHistorySignature)
    RecyclerView recyclerViewInSumHistorySignature;

    //潜在客户，
    private ArrayList<FileSignatureManage> mDataResources = new ArrayList<FileSignatureManage>();

    //列表的历史记录：
    private FileSignatureItemAdapter fileSignatureItemAdapter;

    //最后一条上传的id的信息内容
    private int pagination_upLoad = Parameterkey.pageNum_default_first;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        if (mDataResources == null) {
            mDataResources = new ArrayList<>();
        }

        processExtraData();

        initloading();

        initViews();

        gainDatas();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_signature_sum_history;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }


    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        //卡券发放记录：
        toolbarHelper.setTitle(getString(R.string.title_signature_manage_history));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里是什么都没有的；
        toolbarHelper.setLayoutRight(false, 1, "", null);
//        toolbarHelper.setLayoutRight(false, 1, "", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //布局的适配器填充，下拉刷新等等；
        recyclerViewInSumHistorySignature.setLayoutManager(new MyLinearLayoutManager(this));
        fileSignatureItemAdapter = new FileSignatureItemAdapter(R.layout.signaturemainadapter, mDataResources, ExtraValue.VALUE_JUMPFROM_SIGNATURE_HISTROY_ACTIVITY_ONITEM_CLICK_INTO);
        recyclerViewInSumHistorySignature.setAdapter(fileSignatureItemAdapter);
        fileSignatureItemAdapter.notifyDataSetChanged();

        fileSignatureItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                FileSignatureManage fileSignatureManage = (FileSignatureManage) adapter.getItem(position);

                if (fileSignatureManage != null) {

                    switch (view.getId()) {

                        case R.id.textViewFileSignPartyBPhone: {

                            clickButton_toCallPhone(SignatureSumHistoryActivity.this, fileSignatureManage.getClientPhone(), CallHistoryBusinessType.BUSINESSTYPE_7.getIndex());

                            break;
                        }

                        default:
                            break;
                    }

                }
            }
        });

        fileSignatureItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                FileSignatureManage fileSignatureManage = (FileSignatureManage) adapter.getItem(position);

                if (fileSignatureManage != null) {

                    // : 2023-07-13 15:07 跳转到这个客户的详情页面
                    Bundle extra_bundle = new Bundle();

                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMPFROM_SIGNATURE_HISTROY_ACTIVITY_ONITEM_CLICK_INTO);
                    extra_bundle.putParcelable(ExtraKey.EXTRA_SIGNATRUE_MANAGE_ITEM_BEAN, fileSignatureManage);

                    ActivityUtils.startActivity(extra_bundle, SignatureDetailActivity.class);

                }
            }
        });


        //下拉刷新等
        refreshLayoutInSumHistorySignature.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

//                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//
//                            getServerDatas_for_rice_tick_history();
//
//                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//
//                            getServerDatas();
//
//                        } else {
//                            //额外的
//                            getServerDatas();
//                        }

                        getServerDatas();

                        refreshLayout.finishLoadMore();

                    }
                });
            }
        });


    }

    @Override
    protected void gainDatas() {

        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

//            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//
//                getServerDatas_for_rice_tick_history();
//
//            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//
//                getServerDatas();
//
//            } else {
//                //额外的
//                getServerDatas();
//            }

        } else {
            netWorkError();
            setEnableLoadmore(refreshLayoutInSumHistorySignature, false);
        }


    }

    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,

        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getShopLatentCustomerList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getInformationManageListByCreateBy_signature(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(SignatureSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<FileSignatureOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        if (mDataResources != null && mDataResources.isEmpty()) {

                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        }
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInSumHistorySignature, true);
                    }
                }).subscribe(new Consumer<FileSignatureOutSide>() {
                    @Override
                    public void accept(FileSignatureOutSide fileSignatureOutSide) throws Throwable {

                        method_handler_success(fileSignatureOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错；
                    }
                });

//        // : 2023-10-26 14:13 测试一条假数据
//        // : 2023-10-25 10:14 添加一条假数据，测试代码要删除的；
//        FileSignatureManage fileSignatureManage = new FileSignatureManage();
//        fileSignatureManage.setCreateSerialNo("编号12345678");
//        fileSignatureManage.setSignTemplateName("汽车销售合同");//模板名称
//        fileSignatureManage.setSignTemplateStatus("已签约");
//        fileSignatureManage.setCreateTime("2023-11-14 11:10:20");
//
//        mDataResources.add(fileSignatureManage);
//        fileSignatureItemAdapter.notifyDataSetChanged();

    }

    //多个接口通用的
    private void method_handler_success(FileSignatureOutSide _fileSignatureOutSide) {

        if (_fileSignatureOutSide != null) {

            ArrayList<FileSignatureManage> fileSignatureManageArrayList = _fileSignatureOutSide.getDataList();

            if (fileSignatureManageArrayList != null && !fileSignatureManageArrayList.isEmpty()) {
                if (mDataResources != null) {
                    mDataResources.addAll(fileSignatureManageArrayList);
                }
            }

        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDataResources != null && mDataResources.isEmpty()) {

            if (refreshLayoutInSumHistorySignature != null) {
                refreshLayoutInSumHistorySignature.setEnableLoadMore(false);
            }

            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

        }

        if (fileSignatureItemAdapter != null) {
            fileSignatureItemAdapter.notifyDataSetChanged();
        }

        pagination_upLoad = _fileSignatureOutSide.getNextPagination();

        //对列表改造：
        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
            setFinishLoadMoreWithNoMoreData(refreshLayoutInSumHistorySignature, true);
        } else {
            setEnableLoadmore(refreshLayoutInSumHistorySignature, true);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (fileSignatureItemAdapter != null) {
            fileSignatureItemAdapter.notifyDataSetChanged();
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);
//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);
            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);

            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);

        }

    }
}